package code.class4;


public class TestDemo {
    public static void main(String[] args) {
        int[] gas = {1, 2, 3, 4, 5}; // 油量
        int[] cost = {3, 4, 5, 1, 2}; // 距离
        //          -2 -2 -3  3  3
        int startIndex = canCompleteCircuit(gas, cost);
        System.out.println("startIndex = " + startIndex);
    }

    private static int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        int l = 0, r = 0, sum;
        for (; r < n; l = r + 1, r = l) {
            sum = 0;
            int k = gas[r % n] - cost[r % n];
            while (sum + k >= 0) {
                if (r - l + 1 == n) {
                    return l;
                }
                sum += k;
                r++;
            }
        }
        return -1;
    }


}
